package entities;

/*
 * version 2.0 by Bush
 * 		1. fixed bug in getRoomById()
 * 		2. fixed bug in checkSchedule()
 * version 1.0
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;

public class Room {
	private String id;
	private int quota;
	private ArrayList<String> m_arrRoomSectionIds = new ArrayList<String>();
	private static HashMap<String, Room> m_mapAllRooms = new HashMap<String, Room>();

	public Room(String id, int quota) {
		this.id = id;
		this.quota = quota;

		if (m_mapAllRooms.get(id) == null)
			m_mapAllRooms.put(id, this);
	}

	public static Room getRoomById(String targetId) {
		return m_mapAllRooms.get(targetId);
	}

	public static ArrayList<Room> getRoomsByQuota(int quota) {
		ArrayList<Room> result = new ArrayList<Room>();
		Iterator<String> roomId = m_mapAllRooms.keySet().iterator();
		while (roomId.hasNext()) {
			Room rm = m_mapAllRooms.get(roomId.next());
			if (rm.quota == quota)
				result.add(rm);
		}
		return result;
	}

	public String getRoomId() {
		return this.id;
	}

	@SuppressWarnings("unchecked")
	public void addSection(String sectionId) {
		m_arrRoomSectionIds.add(sectionId);
		Collections.sort(m_arrRoomSectionIds, new byLineLength());
	}

	public static int getNumOfRoom() {
		return m_mapAllRooms.size();
	}

	public String[] getRelatedSectionIds() {
		String[] result = new String[m_arrRoomSectionIds.size()];
		int index = 0;
		for (String sectionId : m_arrRoomSectionIds) {
			result[index++] = sectionId;
		}
		return result;
	}

	@SuppressWarnings("rawtypes")
	public class byLineLength implements java.util.Comparator {
		public int compare(Object o1, Object o2) {

			Section s1 = Section.getSectionById((String) o1);
			Section s2 = Section.getSectionById((String) o2);
			return s1.getSectionStartTime().toInt()
					- s2.getSectionStartTime().toInt();
		}
	}

	public static void clear() {
		m_mapAllRooms.clear();
	}
}
